from time import sleep

from vnpy_datarecorder import DataRecorderApp, RecorderEngine

from trader.gateway.backtester.backtester_bar_gateway import BackTesterBarGateway
from trader.gateway.backtester.backtester_tick_gateway import BackTesterTickGateway
from vnpy.event import EventEngine, Event
from vnpy.trader.constant import Exchange
from vnpy.trader.engine import MainEngine
from vnpy.trader.object import ContractData
from vnpy.trader.ui import MainWindow, create_qapp
from vnpy.trader.event import EVENT_LOG

from vnpy_ctp import CtpGateway
from vnpy_rpcservice import RpcServiceApp
from vnpy_rpcservice.rpc_service.engine import EVENT_RPC_LOG


def main_ui():
    """启动图形化界面模式的主函数"""
    qapp = create_qapp()

    event_engine = EventEngine()

    main_engine = MainEngine(event_engine)

    main_engine.add_gateway(CtpGateway)
    main_engine.add_app(RpcServiceApp)

    main_window = MainWindow(main_engine, event_engine)
    main_window.showMaximized()

    qapp.exec()


def process_log_event(event: Event):
    """处理日志事件，将日志信息打印到控制台"""
    log = event.data
    msg = f"{log.time}\t{log.msg}"
    print(msg)


def main_terminal():
    """启动命令行模式的主函数"""
    event_engine = EventEngine()
    event_engine.register(EVENT_LOG, process_log_event)
    event_engine.register(EVENT_RPC_LOG, process_log_event)

    main_engine = MainEngine(event_engine)
    ctp_gateway(main_engine)
    rpc_service(main_engine)

    # record_engine(main_engine)

    back_tester(main_engine)

    while True:
        sleep(1)


def back_tester(main_engine: MainEngine):
    main_engine.add_gateway(BackTesterTickGateway)
    main_engine.add_gateway(BackTesterBarGateway)
    main_engine.write_log("加载回测网关")


def record_engine(main_engine: MainEngine):
    record_engin:RecorderEngine = main_engine.add_app(DataRecorderApp)
    record_engin.register_event()
    record_engin.add_tick_recording("au2506.SHFE")
    contract: ContractData = ContractData(gateway_name="CTP", exchange=Exchange.SHFE, symbol="au2506", name="contract_test", product=None, size=0, pricetick=None)
    record_engin.subscribe(contract)


def ctp_gateway(main_engine: MainEngine):
    main_engine.add_gateway(CtpGateway)
    # 示范CTP连接配置，实际使用时需要填写真实的配置
    setting = {
        "用户名": "10633",
        "密码": "123456",
        "经纪商代码": "",
        "交易服务器": "tcp://121.37.80.177:20002",
        "行情服务器": "tcp://121.37.80.177:20004",
        "产品名称": "",
        "授权编码": ""
    }
    # SIMNOW访问配置
    # setting = {
    #     "用户名": "230563",
    #     "密码": "pa55w0Rd@simnow",
    #     "经纪商代码": "9999",
    #     "交易服务器": "180.168.146.187:10201",
    #     "行情服务器": "180.168.146.187:10211",
    #     "产品名称": "simnow_client_test",
    #     "授权编码": "0000000000000000",
    #     "产品信息": ""
    # }
    main_engine.connect(setting, "CTP")
    main_engine.write_log('连接CTP服务器')
    sleep(10)
    # req: SubscribeRequest = SubscribeRequest(symbol="au2409", exchange=Exchange.SHFE)
    # main_engine.subscribe(req, "CTP")
    # main_engine.write_log('订阅行情')


def rpc_service(main_engine: MainEngine):
    rpc_engine = main_engine.add_app(RpcServiceApp)
    rep_address = "tcp://127.0.0.1:2014"
    pub_address = "tcp://127.0.0.1:4102"
    rpc_engine.start(rep_address, pub_address)
    main_engine.write_log("RPC启动完成")


if __name__ == "__main__":
    # 注释掉的代码表示不执行该部分代码
    # Run in GUI mode
    # main_ui()

    # Run in CLI mode
    main_terminal()
